package jdesktop.drag;

import java.awt.*;

public class RectangleBoundsConstraint implements BoundsConstraint
{
    private Rectangle outer;
    private Rectangle inner;

    public RectangleBoundsConstraint()
    {
    }

    public RectangleBoundsConstraint(Rectangle outer)
    {
        this.outer = outer;
    }

    public Rectangle getInner()
    {
        return inner;
    }

    public void setInner(Rectangle inner)
    {
        this.inner = inner;
    }

    public Rectangle getOuter()
    {
        return outer;
    }

    public void setOuter(Rectangle outer)
    {
        this.outer = outer;
    }

    public void constrain(Rectangle r)
    {
        // todo - check if width/heigh are greater than outer rect width/height
        if (inner!=null)
            constrainInner(r);
        constrainOuter(r);
        
    }

    private void constrainInner(Rectangle r)
    {
        if (r.x<=inner.x)
            r.x = outer.x;
        if (r.y<=inner.y)
            r.y = outer.y;

        // align right/bottom side of over, don't change size.
        if (r.x+r.width>inner.x+inner.width)
            r.x = outer.x+outer.width-r.width;
        if (r.y+r.height>inner.y+inner.height)
            r.y = outer.y+outer.height-r.height;
    }

    private void constrainOuter(Rectangle r)
    {
        if (r.x<=outer.x)
            r.x = outer.x;
        if (r.y<=outer.y)
            r.y = outer.y;

        // align right/bottom side of over, don't change size.
        if (r.x+r.width>outer.x+outer.width)
            r.x = outer.x+outer.width-r.width;
        if (r.y+r.height>outer.y+outer.height)
            r.y = outer.y+outer.height-r.height;
    }
}
